package com.blog.cloud.captcha.service.impl;

import cn.hutool.core.util.StrUtil;
import com.blog.cloud.captcha.service.CaptchaService;
import com.blog.cloud.captcha.vo.CaptchaVO;
import com.wf.captcha.SpecCaptcha;
import com.wf.captcha.base.Captcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service("captchaService")
public class CaptchaServiceImpl implements CaptchaService {

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @Override
    public CaptchaVO generate() {
        // 生成验证码key唯一标识
        String key = UUID.randomUUID().toString();

        // 生成验证码
        SpecCaptcha captcha = new SpecCaptcha(150, 40);
        // 内容字符个数
        captcha.setLen(5);
        captcha.setCharType(Captcha.TYPE_DEFAULT);
        String image = captcha.toBase64();

        redisTemplate.opsForValue().set(key,captcha.text(),1L, TimeUnit.MINUTES);

        CaptchaVO captchaVO = new CaptchaVO();
        captchaVO.setKey(key);
        captchaVO.setImage(image);
        return captchaVO;
    }

    @Override
    public Boolean validate(String key, String code) {
        if (StrUtil.isBlank(key) || StrUtil.isBlank(code)) {
            return false;
        }
        String captcha = (String) redisTemplate.opsForValue().get(key);
        if (StrUtil.isBlank(captcha)) {
            return false;
        }
        redisTemplate.delete(key);
       return captcha.equalsIgnoreCase(code);
    }

}
